<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>canvas 动画</title>
<style type="text/css">
/*=== base style===*/
article,aside,dialog,footer,header,section,footer,nav,figure,menu{display:block; margin:0; padding:0;}
body, h1, h2, h3, h4, h5, h6, p, ul, ol, dl, dt, dd, li, img,div,span,em,i,a,input {padding: 0;margin: 0;border: none;}
ul,li {list-style: none;}
h1, h2,h3,h4, h5, h6{font-weight:normal;}
body{font-family: "微软雅黑"; font-size: 12px;}
.clearfix:after {content:"";height:0;display:block;clear:both;}
.clearfix {zoom:1;}
img{vertical-align:top;}
em,i{font-style:normal;}
a img{border:0px;}
a,a:hover,ins{ text-decoration:none;}
area{ outline:none}
.width990{width: 990px; margin: 0px auto;}
.zyp_wrap{width: 100%; margin: 0px auto;font-family: "微软雅黑"; font-size: 12px;}


.cav_wrap{width: 700px; height: 550px; margin: 30px auto;}
#cav{ border: 1px solid #ccc;}
</style>
</head>
<body>
<div class="cav_wrap">
   <canvas id="cav" width="700" height="550"></canvas>
</div>
<!-- <img src="tmall.png"> -->
<script type="text/javascript">

//<注意大坑>：canvas的"宽度高度"必须写在便签内

//定义图形对象,坐标位置
var pic_att={
   x:60,
   y:20,
   speed:5
}
function drawPic(){
   var mycv = document.getElementById("cav"); //获取canvas对象
   var ctx = mycv.getContext("2d");

   ctx.clearRect(0,0,700,550);//清楚画布｛x,y,width,heigth｝
   ctx.fillStyle="#FF0000";
   ctx.beginPath();
   ctx.arc(pic_att.x,pic_att.y,15,0,Math.PI*2,true);
   ctx.closePath();
   ctx.fill();
}
drawPic();

// keycode:37(左),38(上),39(右),34(下),
function move(keycode){
   if(keycode==37){
      if(pic_att.x>15){
         pic_att.x=pic_att.x-pic_att.speed;
         drawPic();
      }
   }
   if(keycode==39){
      if(pic_att.x<(700-15)){
         pic_att.x=pic_att.x+pic_att.speed;
         drawPic();
      }
   }
   if(keycode==38){
      if(pic_att.y>15){
         pic_att.y=pic_att.y-pic_att.speed;
         drawPic();
      }
   }
   if(keycode==40){
      if(pic_att.y<(500-15)){
         pic_att.y=pic_att.y+pic_att.speed;
         drawPic();
      }
   }
}

// 侦听键盘事件
addEventListener("keydown",function (e){
   // console.log(e.keyCode);
   move(e.keyCode);
}, false);

</script>
</body>
</html>